package com.cn.demo.config;

import com.cn.demo.service.OrderService;
import com.cn.demo.util.CommonConstants;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.redisson.api.map.event.EntryEvent;
import org.redisson.api.map.event.EntryExpiredListener;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀成功的用户，30分钟过期
 *
 * @author wangjf
 * @version 1.0
 * @createDate 2019/11/15 16:45
 * @projectName test
 */
@Component
public class SeckillLockUserCache implements InitializingBean {

    @Autowired
    private RedissonClient redisson;
    //userId和订单no
    private RMapCache<String, String> lockMap;
    @Autowired
    private OrderService orderService;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (lockMap == null) {
            lockMap = redisson.getMapCache("lockMap");
            //过期时判断是否支付，如果未支付则把订单设置为取消
            lockMap.addListener(new EntryExpiredListener<String, String>() {
                @Override
                public void onExpired(EntryEvent<String, String> event) {
                    orderService.cancelOrder(event.getKey(),event.getValue());
                }
            });
        }
        Assert.notNull(lockMap, "秒杀锁定初始化失败, lockMap is null");
    }

    /**
     * 清空数据
     * @author: wangjf
     * @createTime: 2019/11/18 10:50
     * @param
     * @return void
     */
    public void clear(){
        lockMap.clear();
    }

    /**
     * 获取值
     *
     * @param userId
     * @return java.lang.Boolean
     * @author: wangjf
     * @createTime: 2019/11/15 16:55
     */
    public String get(String userId) {

        return lockMap.get(userId);
    }

    /**
     * 是否存在key
     * @author: wangjf
     * @createTime: 2019/11/20 11:16
     * @param userId
     * @return java.lang.Boolean
     */
    public Boolean existKey(String userId) {
        String value = lockMap.get(userId);
        if (value == null) {
            return false;
        }
        return true;
    }
    /**
     * put值 30分钟过期
     *
     * @param userId
     * @return void
     * @author: wangjf
     * @createTime: 2019/11/15 16:55
     */
    public void put(String userId,String orderNo) {
        lockMap.put(userId,orderNo, CommonConstants.SECKILL_ORDER_TTL, TimeUnit.MINUTES);
    }

}
